import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';
import 'package:tiktokadult/hj_model/home/module_detail_model.dart';
import 'package:tiktokadult/hj_model/splash/ads_model.dart';
import 'package:tiktokadult/hj_model/video_model.dart';
import 'package:tiktokadult/hj_utils/api_service/vid_service.dart';
import 'package:tiktokadult/tools_base/global_store/local_ads_info_store.dart';

import '../../../tools_base/ad_insert_manager.dart';

class SpecailTopicsController extends GetxController with GetTickerProviderStateMixin {
  final AllSection? originModel;
  SpecailTopicsController(this.originModel);
  final sortTitles = ['最多收藏', '最新上架', '最多观看'];
  int sort = 0;
  List<String> sortParma = ['collect', 'new', 'watch'];
  bool isLoading = true;
  int page = 1;
  RxBool isGridStyle = true.obs; //
  late final TabController tabController = TabController(length: sortTitles.length, vsync: this);
  late final ScrollController scrollController = ScrollController();
  RefreshController? refreshController;
  List<VideoModel> dataSource = [];

  final listADS = <AdsInfoModel>[];
  bool hasFetchADs = false;
  String get title => originModel?.sectionName ?? '';
  RxBool isShowAppMenu = false.obs;

  bool get isFollow => false;
  RxBool isFollowLoading = false.obs;

  @override
  void onInit() {
    super.onInit();
    scrollController.addListener(() {
      if (scrollController.offset > 132) {
        isShowAppMenu.value = true;
      } else {
        isShowAppMenu.value = false;
      }
    });
  }

  @override
  void onReady() {
    super.onReady();
    fetchPageData();
  }

  fetchInsertAds() async {
    final adsList = await getAdvByType(8);
    listADS.clear();
    listADS.addAll(adsList);
    hasFetchADs = true;
  }

  void onTooleAction() {
    isGridStyle.value = !isGridStyle.value;
    update();
  }

  insertListAdsToList() async {
    //
    if (!hasFetchADs) await fetchInsertAds();
    if (listADS.isEmpty) return;
    AdInsertManager.video(dataSource, listADS, adGap: 8);
  }

  fetchPageData({bool isRefresh = true, bool showLoading = false}) async {
    if (isRefresh) {
      page = 1;
    }
    if (showLoading) {
      isLoading = true;
      update();
    }
    final res = await VidService.fetchSectionVideos(originModel?.sectionID ?? '', pageNumber: page, sortType: sortParma[sort]);
    isLoading = false;
    if (isRefresh) {
      dataSource.clear();
      refreshController?.refreshCompleted();
    }
    if (res?.hasNext ?? false) {
      refreshController?.loadComplete();
    } else {
      refreshController?.loadNoData();
    }
    dataSource.addAll(res?.videos ?? []);
    insertListAdsToList();
    page += 1;
    update();
  }
}
